var menuList=[],roleList=[];
var menuTree=[];
$(function(){
	initMenu();
	initMenuTree();
});
function initMenuTree(){
	$.ajax({ 
	     type : "get",
	     url : BSAE_PATH+"/admin/menu/getMenuTree",
	     dataType : 'json',
	     data : {
	     	type:1,
	     },
	     success : function(result) {
		    if (result.code==200 ) { 
			    menuTree=result.data;
		    }
	     } 
    }); 
}
function initMenu(){
	$.ajax({ 
	     type : "get",
	     url : BSAE_PATH+"/admin/menu/getMenuList",
	     dataType : 'json',
	     data : {
	     	type:1,
	     },
	     success : function(result) {
		    if (result.code==200 ) { 
			    menuList=result.data;
			    initRole();
		    }
	     } 
    }); 
}
function initRole(){
	$.ajax({ 
     type : "get",
     url : BSAE_PATH+"/admin/menu/getRoleList",
     dataType : 'json',
     data : {},
     success : function(result) {
	    if (result.code==200 ) { 
		    var htmlStr='';
		    roleList=result.data;
		    for (var i = 0; i < roleList.length; i++) {
		    	var role=roleList[i];
		    	htmlStr+='<tr>';
		    	htmlStr+='<td style="color:red;">'+role.name+'</td>';
		    	htmlStr+='<td style="width: 70%; ">';
		    	var ids=(role.menuList==undefined||role.menuList==null)?[]:role.menuList.split(",");
		    	for (var j = 0; j < ids.length; j++) {
		    		htmlStr+='<span class="badge my-span my-span-info">'+getMenuName(ids[j])+'</span>';
		    	}
		    	htmlStr+='</td>';
			    htmlStr+='<td>'
			       	+'<button type="button" class="btn btn-primary" onclick="addRoleView('+role.id+')"><i class="icon icon-note"></i> &nbsp; 编辑</button> &nbsp;'
			       	+'<button type="button" class="btn btn-danger" onclick="delRole('+role.id+')"><i class="fa fa-trash"></i> &nbsp; 删除</button>'
			       	+'</td>';
				htmlStr+='</tr>';
		    }
		    $("#tbodyList").html(htmlStr);
	    }
     } 
    }); 
}

function getMenuName(id){
	if(id==-1){
		return '';
	}
	for (var i = 0; i < menuList.length; i++) {
		if(menuList[i].id==id){
			return menuList[i].name;
		}
	}
}
function delRole(id){
	layer.confirm('删除不可恢复，是否确定删除？', {
	  btn: ['确定','取消'] //按钮
	}, function(){
	  layer.msg('模拟删除', {icon: 1});
	}, function(){
	  
	});
}
function saveRole(id, name, menuList){
	$.ajax({ 
     type : "post", 
     url : BSAE_PATH+"/admin/menu/saveRole",
     dataType : 'json',
     data : { 
     	id : id,
     	name : name,
     	menuList : menuList,
     },
     success : function(result) {
	    if (result.code==200 ) { 
	    	layer.closeAll();
		    initRole();
	    }else{ 
	       
	    } 
     } 
    });
}


function addRoleView(id){
	layer.open({
	  type: 1,
	  title : (id==-1)?'新增':'编辑',
	  skin: 'layui-layer-rim', //加上边框
	  area: ['600px', '800px'], //宽高
	  content: '<div class="layerDiv">'
	  +'<div class="form-group"><label for="firstname" class="col-sm-2 control-label">角色</label><div class="col-sm-12"><input type="text" class="form-control" id="nameInput" placeholder="请输入"></div></div>'
	  +'<div class="form-group"><label for="firstname" class="col-sm-2 control-label">菜单目录</label><div class="col-sm-12" id="menuTreeDiv"></div></div>'
	 +'</div>',
	 btn: ['确定', '取消'],
	 yes: function(index, layero){
	    var nameInput=$("#nameInput").val();
	    if(nameInput.trim()==''){
	    	layer.msg("角色名不能为空");
	    	return;
	    }
	    var nodes=$('#menuTreeDiv').treeview('getChecked');
	    var ids='';
	    for (var i = 0; i <nodes.length; i++) {
	    	ids+=nodes[i].tags+',';
	    }
	    ids=(ids.length>0)?ids.substring(0,ids.length-1):'';
	    saveRole(id, nameInput, ids);
	 },
	 success: function(layero, index){
	 	var role=null;
	 	for (var i = 0; i < roleList.length; i++) {
	 		if(id==roleList[i].id){
	 			role=roleList[i];
	 			break;
	 		}
	 	}
	 	$("#nameInput").val((role==null)?'':role.name);
	 	$('#menuTreeDiv').treeview({
	 		data: getMuenTree((role==null)?'1':role.menuList),
		 	selectedBackColor:"#FFFFFF",
		 	selectedColor: "#000000",
		 	collapseIcon : "fa fa-minus tree-icon-big",
		 	expandIcon : "fa fa-plus tree-icon-big",
		 	checkedIcon : "icon-check tree-icon-big tree-check",
		 	uncheckedIcon : "icon-ban tree-icon-big tree-uncheck",
		 	showCheckbox: true,
		 	//showTags :true
	 	}).off('click','li.list-group-item').on('click','li.list-group-item',function(){
	 		var nodeid = $(this).data('nodeid');
		    var tree = $("#menuTreeDiv");
		    var node = tree.treeview('getNode', nodeid);
		    
		    if (!node.state.checked) {
		        //处于展开状态则折叠
		        tree.treeview('checkNode', nodeid);
		    } else {
		        //展开
		        tree.treeview('uncheckNode', nodeid);
		    }
		    
	 	}).on('click','span.icon.expand-icon',function(){
	 		var nodeid = $(this).closest('li.list-group-item').data('nodeid');
		    var tree = $("#menuTreeDiv");
		    var node = tree.treeview('getNode', nodeid);
		    if (node.state.expanded) {
		        //处于展开状态则折叠
		        tree.treeview('collapseNode', nodeid);
		    } else {
		        //展开
		        tree.treeview('expandNode', nodeid);
		    }
		    return !1
	 	});
	 }
	});
}
function getMuenTree(ids) {
	var data=[];
	data=changeTree(ids,menuTree);
    return data;
}
function changeTree(ids,menuList){
	var data=[];
	for (var i = 0; i < menuList.length; i++) { 
		var menu= menuList[i];
		var isNode=(menu.list!=undefined&&menu.list!=null&&menu.list.length>0);
		data[data.length]={
			tags: [menu.id],
			text : menu.name+"",
			state :{
				checked : isIds(ids,menu.id),
				expanded :isNode
			},
			backColor:"#FFFFFF",
			color:"#000000",
			icon: isNode?"":"not-node",
			nodes:isNode?changeTree(ids,menu.list):null,
		};
	}
	return data;
}

function isIds(ids,id){
	if(ids==""){
		return false;
	}
	return (","+ids+",").split(","+id+",").length>1;
}


